package com.songlanyun.modules.goods.entity;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.modules.goods.model.values.GoodsSkuTableItem;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.type.TypeReference;
import com.songlanyun.common.drive.RootEntity;
import com.songlanyun.common.utils.SpringContextUtils;
import com.songlanyun.common.utils.custom.ClassConvertUtils;
import com.songlanyun.modules.goods.model.values.SkuSet;
import com.songlanyun.modules.singlegoods.entity.ProductSingleGoodsEntity;
import com.songlanyun.modules.singlegoods.service.ProductSingleGoodsService;
import lombok.Data;

import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;


/**
 * 商品的规格的关系表（一个商品可能会有多个规格，各个规格中要关联单品）
 *
 * @author lubo
 * @email sunlightcs@gmail.com
 * @date 2020-11-05 10:01:59
 */
@Data
@TableName("yxt_product_goods_sku_relation")
public class GoodsSku extends RootEntity<Long, GoodsGroupRelation> implements Serializable {
    private static final long serialVersionUID = 1L;


    {
        singleGoodsId = 0L;
        exchangePoint = BigDecimal.ZERO;
        singleGoodsTitle = "";
        singleGoodsCode = "";
        salePrice = BigDecimal.valueOf(0);
        marketPrice = BigDecimal.valueOf(0);
        skuHashCode = "";
        skuSetValue = "";
        barCode = "";
        cover = "";
        volume = BigDecimal.valueOf(0);
        weight = BigDecimal.valueOf(0);
        thirdSkuId = 0L;
        agreementPrice = BigDecimal.ZERO;
        thirdCostPrice = BigDecimal.ZERO;
        guidePrice = BigDecimal.ZERO;
    }

    /**
     *
     */
    @TableId
    private Long id;

    private Long shopId;
    /**
     * 商品id
     */
    private Long goodsId;
    /**
     * 单品id
     */
    private Long singleGoodsId;

    /**
     * 单品码
     */
    private String singleGoodsCode;

    /**
     * 单品名称（容余）
     */
    private String singleGoodsTitle;

    /**
     * 销售价
     */
    @DecimalMin(value = "0",message = "销售价最小是0")
    @DecimalMax(value = "99999999",message = "销售价最大是99999999")
    private BigDecimal salePrice;
    /**
     * 市场价
     */
    @DecimalMin(value = "0",message = "市场价最小是0")
    @DecimalMax(value = "99999999",message = "市场价最大是99999999")
    private BigDecimal marketPrice;
    /**
     * 重量
     */
    private BigDecimal weight;
    /**
     * 体积
     */
    private BigDecimal volume;


    /**
     * 商品规格编码
     */
    private String barCode;
    /**
     * 使用积分
     */
    private BigDecimal exchangePoint;
    /**
     * 封面图片
     */
    private String cover;

    /**
     * 规格名（蓝色,175,男）
     */
    private String skuSetName;

    /**
     * 所有属性值哈希值
     * 1111|1234|4556
     */
    private String skuHashCode;


    /**
     * 规格组合配置（Json数据:
     * [
     * value:{"name":"黄色","id":"123334"}}
     * value:{"name":"175cm","id":"14545233"}}
     * value:{"name":"全棉","id":"12345453"}}
     * ]
     * ）
     */


    @TableField(exist = false)
    private List<SkuSet> skuSets;
    public void setSkuSets(List<SkuSet> skuSets) {
        this.skuSets = skuSets;

        if (this.skuSets==null || this.skuSets.size()==0) {
            this.setSkuHashCode("");
            this.skuSetName = "";
            this.skuSetValue = "";
            return;
        }
        List<String> codeList  = this.skuSets.stream().map(item -> {
            return item.getValue().getId().toString();
        }).sorted().collect(Collectors.toList());

        this.setSkuHashCode(String.join("|", codeList));
        this.skuSetName = StringUtils.join(this.skuSets.stream().map(o -> o.getValue().getName()).toArray(), ";");
        this.skuSetValue  =  JSONUtil.toJsonStr(this.skuSets);
    }


    /**
     * 规格组合配置的子符串设置（Json数据:
     * [
     * {"head":{"name":"颜色","id":"1233"},value:{"name":"黄色","id":"123334"}}
     * {"head":{"name":"尺码","id":"12345453"},value:{"name":"175cm","id":"14545233"}}
     * {"head":{"name":"面料","id":"1233454"},value:{"name":"全棉","id":"12345453"}}
     * ]
     * ）
     */
    @JsonIgnore
    private String skuSetValue;
    public void setSkuSetValue(String skuSetValue) {
        this.skuSetValue  = skuSetValue;
        if (StringUtils.isEmpty(this.skuSetValue)) {
            this.skuSets = new ArrayList<>();
        } else {
            try {
                this.skuSets = ClassConvertUtils.stringToClassSnake(skuSetValue, new TypeReference<List<SkuSet>>() {
                });
            } catch (IOException e) {
                throw new RRException("商品规格无法转Map");
            }
        }
    }



    @JsonIgnore
    @TableField(exist = false)
    private ProductSingleGoodsEntity singleGoods;
    public ProductSingleGoodsEntity loadSingleGoods() {

        if (this.singleGoods == null) {
            return ((ProductSingleGoodsService) SpringContextUtils.getBean("productSingleGoodsService")).getById(this.getSingleGoodsId());
        }
        return this.singleGoods;
    }

    @TableField(exist = false)
    public BigDecimal costPrice;
    /**
     * 获得单品成本价
     * @return
     */
    public BigDecimal getCostPrice() {
        ProductSingleGoodsEntity singleGoods = loadSingleGoods();
        if (singleGoods == null) {
            return BigDecimal.ZERO;
        }
        return singleGoods.getCostPrice();
    }

//    /**
//     * 读数据时调用一次方法
//     */
//    public void getMapSkuSets() {
//        if (StringUtils.isEmpty(this.skuSetValue)) {
//            this.skuSets = new ArrayList<>();
//            return;
//        }
//        try {
//            this.skuSets = ClassConvertUtils.stringToClassSnake(skuSetValue, new TypeReference<List<SkuSet>>() {
//            });
//        } catch (IOException e) {
//            throw new Error("商品参数无法转Map");
//        }
//    }


//    /**
//     * 持就到数据库时要调用一次方法
//     */
//
//    public void saveEntityProcess() {
//        mapSingleGoods();
//        if (StringUtils.isEmpty(this.skuSetValue)) {
//            this.skuSets = new ArrayList<>();
//            this.setSkuHashCode("");
//            this.skuSetName = "";
//            return;
//        }
//        try {
//            this.skuSets = ClassConvertUtils.stringToClassSnake(skuSetValue, new TypeReference<List<SkuSet>>() {
//            });
//        } catch (IOException e) {
//            throw new Error("商品参数无法转Map");
//        }
//        List<String> codeList = new ArrayList<>();
//        this.skuSets.forEach(item -> {
//            codeList.add(item.getValue().getId().toString());
//        });
//
//        Collections.sort(codeList);
//        setSkuHashCode(String.join("|", codeList));
//        if (this.skuSets.size() == 0) {
//            this.skuSetName = "";
//        } else {
//            this.skuSetName = StringUtils.join(this.skuSets.stream().map(o -> o.getValue().getName()).toArray(), ";");
//        }
//    }


//     /**
//     * 持就到数据库时要调用一次方法
//     */
//    public void saveEntityProcess() {
//        if (this.skuSets==null || this.skuSets.size()==0) {
//            this.setSkuHashCode("");
//            this.skuSetName = "";
//            return;
//        }
//        List<String> codeList = new ArrayList<>();
//        this.skuSets.forEach(item -> {
//            codeList.add(item.getValue().getId().toString());
//        });
//        //Collections.sort(codeList);
//        this.setSkuHashCode(String.join("|", codeList));
//        this.skuSetName = StringUtils.join(this.skuSets.stream().map(o -> o.getValue().getName()).toArray(), ";");
//    }


    @Override
    public boolean isEmpty() {
        return singleGoodsId == 0L && StringUtils.isEmpty(singleGoodsCode) && StringUtils.isEmpty(barCode);
    }

    @Override
    public Long getIdentity() {
        return getId();
    }


    /**
     * 第三方的成本价
     */
    private BigDecimal  thirdCostPrice;


    /**
     * 规格协议价
     */
    private BigDecimal agreementPrice;


    /**
     * 规格指导价
     */
    private BigDecimal guidePrice;


    /**
     * 第三方的skuId,用来与第三方下单，发货，售后时用的
     */
    private Long thirdSkuId;

}
